<template>
  <div class="min-h-screen p-2 bg-gradient-to-r from-blue-50 to-blue-100">
    <div class="max-w-5xl mx-auto bg-white rounded-xl shadow-sm overflow-hidden">
      <!-- 标题栏 -->
      <div class="bg-blue-600 px-6 py-4">
        <h1 class="text-xl font-semibold text-white">风控部物流残次审核</h1>
      </div>

      <!-- 主要内容区 -->
      <div class="p-4 space-y-6">
        <!-- 第一行：基本信息 -->
        <div class="grid grid-cols-2 md:grid-cols-4 gap-4">
          <div class="space-y-1">
            <p class="text-xl font-semibold text-gray-500">门店名称</p>
            <p class="font-medium text-xl">{{ formData.storeName || '--' }}</p>
          </div>
          <div class="space-y-1">
            <p class="text-xl font-semibold text-gray-500">提报人</p>
            <p class="font-medium text-xl">{{ formData.staffName || '--' }}</p>
          </div>
          <div class="space-y-1">
            <p class="text-xl font-semibold text-gray-500">残次单号</p>
            <p class="font-medium text-xl">{{ formData.billId || '--' }}</p>
          </div>
          <div class="space-y-1" v-if="formData.oaBillId">
            <p class="text-xl font-semibold text-gray-500">钉钉单号</p>
            <p class="font-medium text-xl">{{ formData.oaBillId }}</p>
          </div>
        </div>

        <!-- 第二行：商品信息 -->
        <div class="grid grid-cols-2 md:grid-cols-5 gap-4">
          <div class="space-y-1">
            <p class="text-xl font-semibold text-gray-500">商品名称</p>
            <p class="font-medium text-xl">{{ formData.itemName || '--' }}</p>
          </div>
          <div class="space-y-1">
            <p class="text-xl font-semibold text-gray-500">商品编号</p>
            <p class="font-medium text-xl">{{ formData.itemId || '--' }}</p>
          </div>
          <div class="space-y-1">
            <p class="text-xl font-semibold text-gray-500">商品品类</p>
            <p class="font-medium text-xl">{{ formData.className || '--' }}</p>
          </div>
          <div class="space-y-1">
            <p class="text-xl font-semibold text-gray-500">商品价格</p>
            <p class="font-medium text-xl text-red-600">{{ formData.sellPrice ? `¥${formData.sellPrice}` : '--' }}</p>
          </div>
          <div class="space-y-1">
            <p class="text-xl font-semibold text-gray-500">残次品数量</p>
            <p class="font-medium text-xl text-red-600">{{ formData.posQty }}</p>
          </div>
        </div>

        <div class="grid grid-cols-2 md:grid-cols-5 gap-4">
          <div class="space-y-1">
            <p class="text-xl font-semibold text-gray-500">运单号</p>
            <p class="font-medium text-xl" style="color: red">{{ formData.ydh !== ' ' ?  formData.ydh : '无' }}</p>
          </div>
          <div class="space-y-1">
            <p class="text-xl font-semibold text-gray-500">箱号</p>
            <p class="font-medium text-xl" style="color: red">{{ formData.xh !== ' ' ? formData.xh : '无' }}</p>
          </div>
        </div>
        <div class="flex gap-4 text-center justify-center">
          <p class="text-xl font-semibold text-gray-500 ">物流单号</p>
          <p class="font-medium text-xl">{{ formData.wlBillId }}</p>
        </div>
        <div class="flex gap-4 text-center justify-center">
          <p class="text-xl font-semibold text-gray-500 ">残次审核状态</p>
          <p class="font-medium text-xl" v-if="formData.shStatus === '999'" style="color: red">已终止</p>
          <p class="font-medium text-xl" v-if="formData.shStatus === '000'" style="color: red">门店未确认</p>
          <p class="font-medium text-xl" v-if="formData.shStatus === '001'" style="color: red">门店已确认</p>
          <p class="font-medium text-xl" v-if="formData.shStatus === '002'" style="color: red">区域经理已审核</p>
          <p class="font-medium text-xl" v-if="formData.shStatus === '003'" style="color: red">物流部已审核</p>
        </div>
        <div class="flex gap-4 text-center justify-center">
          <p class="text-xl font-semibold text-gray-500 ">残次审核状态</p>
          <p class="font-medium text-xl" v-if="formData.status === '001'" style="color: red">未审核</p>
          <p class="font-medium text-xl" v-if="formData.status === '004'" style="color: red">已审核</p>
        </div>
        <div class="flex gap-4 text-center justify-center">
          <p class="text-xl font-semibold text-gray-500 ">提报时间</p>
          <p class="font-medium text-xl">{{ formData.uptime }}</p>
        </div>


        <!-- 第三行：残次描述 -->
        <div class="border rounded-lg p-4">
          <p class="text-xl text-gray-500 mb-2">残次描述</p>
          <p class="text-sm leading-5" style="color: red; font-weight: bold">{{ formData.remark || '--' }}</p>
        </div>

        <!-- 第四行：媒体展示 -->
        <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
          <div class="border rounded-lg p-4">
            <p class="text-xl text-gray-500 mb-2">残次视频</p>
            <div v-if="formData.fj !== ' ' && formData.fj" class="aspect-video bg-black rounded overflow-hidden">
              <video controls class="w-full h-full">
                <source :src="formData.fj" type="video/mp4">
              </video>
            </div>
            <div v-else class="text-gray-400 text-sm py-8 text-center">
              暂无视频
            </div>
          </div>
        </div>
        <!-- 第四行：媒体展示 -->
        <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
          <div class="border rounded-lg p-4">
            <p class="text-xl text-gray-500 mb-2">
              {{
                (formData.wlBillId && formData.wlBillId.trim() !== '' &&
                    formData.bffj && formData.bffj.trim() !== '')
                    ? '残次商品包裹视频'
                    : '报废视频'
              }}
            </p>
            <div v-if="formData.bffj && formData.bffj !== ' '" class="aspect-video bg-black rounded overflow-hidden">
              <video controls class="w-full h-full">
                <source :src="formData.bffj" type="video/mp4">
              </video>
            </div>
            <div v-else class="text-gray-400 text-sm py-8 text-center">
              暂无视频
            </div>
          </div>
        </div>

        <!-- 审核操作 -->
        <div class="flex flex-col sm:flex-row justify-end gap-3 pt-4 border-t">
          <button
              @click="showRejectDialog"
              :disabled="buttonsDisabled"
              :class="[
      'px-4 py-2 text-sm rounded transition',
      buttonsDisabled
        ? 'bg-gray-200 text-gray-500 cursor-not-allowed'
        : 'bg-white border border-red-500 text-red-500 hover:bg-red-50'
    ]"
          >
            风控驳回
          </button>
          <!-- 新增报废按钮 -->
          <button
              @click="showScrapDialog"
              :disabled="buttonsDisabled"
              :class="[
        'px-4 py-2 text-sm rounded transition',
        buttonsDisabled
          ? 'bg-gray-200 text-gray-500 cursor-not-allowed'
          : 'bg-amber-600 text-white hover:bg-amber-700'
      ]"
          >
            报废视频不合格
          </button>
          <button
              @click="handleApprove"
              :disabled="buttonsDisabled"
              :class="[
      'px-4 py-2 text-sm rounded transition',
      buttonsDisabled
        ? 'bg-gray-200 text-gray-500 cursor-not-allowed'
        : 'bg-blue-600 text-white hover:bg-blue-700'
    ]"
          >
            风控审核
          </button>
        </div>

        <!-- 驳回原因弹窗 -->
        <div v-if="rejectDialogVisible"
             class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
          <div class="bg-white rounded-lg shadow-xl w-full max-w-md">
            <div class="p-6">
              <h3 class="text-lg font-medium text-gray-900 mb-4">请输入驳回原因</h3>
              <textarea
                  v-model="rejectReason"
                  class="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500"
                  rows="4"
                  placeholder="请详细说明驳回原因..."
              ></textarea>
              <div class="mt-4 flex justify-end space-x-3">
                <button
                    @click="cancelReject"
                    class="px-4 py-2 text-sm text-gray-700 bg-white border border-gray-300 rounded-md hover:bg-gray-50"
                >
                  取消驳回
                </button>
                <button
                    @click="submitReject"
                    :disabled="rejectLoading"
                    class="px-4 py-2 text-sm text-white bg-red-600 rounded-md hover:bg-red-700 disabled:bg-red-300"
                >
                  {{ rejectLoading ? '提交中...' : '提交驳回' }}
                </button>
              </div>
            </div>
          </div>
        </div>


        <!-- 报废原因弹窗 -->
        <TransitionRoot appear :show="isScrapOpen" as="template">
          <Dialog as="div" @close="closeScrapDialog" class="relative z-10">
            <TransitionChild
                as="template"
                enter="duration-300 ease-out"
                enter-from="opacity-0"
                enter-to="opacity-100"
                leave="duration-200 ease-in"
                leave-from="opacity-100"
                leave-to="opacity-0"
            >
              <div class="fixed inset-0 bg-black bg-opacity-25"/>
            </TransitionChild>

            <div class="fixed inset-0 overflow-y-auto">
              <div class="flex min-h-full items-center justify-center p-4 text-center">
                <TransitionChild
                    as="template"
                    enter="duration-300 ease-out"
                    enter-from="opacity-0 scale-95"
                    enter-to="opacity-100 scale-100"
                    leave="duration-200 ease-in"
                    leave-from="opacity-100 scale-100"
                    leave-to="opacity-0 scale-95"
                >
                  <DialogPanel
                      class="w-full max-w-md transform overflow-hidden rounded-2xl bg-white p-6 text-left align-middle shadow-xl transition-all"
                  >
                    <DialogTitle as="h3" class="text-lg font-medium leading-6 text-gray-900">
                      {{ dialogConfig.title }}
                    </DialogTitle>
                    <div class="mt-4">
                      <label class="block text-sm font-medium text-gray-700 mb-2">
                        不合格原因（必填）
                      </label>
                      <textarea
                          v-model="scrapReason"
                          rows="3"
                          class="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500"
                          :placeholder="dialogConfig.placeholder"
                      ></textarea>
                    </div>

                    <div class="mt-6 flex justify-end gap-3">
                      <button
                          type="button"
                          class="px-4 py-2 text-sm bg-gray-100 text-gray-700 rounded-md hover:bg-gray-200"
                          @click="closeScrapDialog"
                      >
                        取消驳回不合格信息
                      </button>
                      <button
                          type="button"
                          :disabled="!scrapReason"
                          :class="[
                    'px-4 py-2 text-sm text-white rounded-md',
                    scrapReason
                      ? 'bg-amber-600 hover:bg-amber-700'
                      : 'bg-amber-300 cursor-not-allowed'
                  ]"
                          @click="confirmScrap"
                      >
                        确认驳回不合格信息
                      </button>
                    </div>
                  </DialogPanel>
                </TransitionChild>
              </div>
            </div>
          </Dialog>
        </TransitionRoot>


      </div>
    </div>
  </div>
</template>

<script setup>
import {ref, onMounted, computed} from 'vue'
import axios from 'axios'
import {useRoute} from "vue-router";
import {ElMessage, ElMessageBox} from "element-plus";
import {
  TransitionRoot,
  TransitionChild,
  Dialog,
  DialogPanel,
  DialogTitle,
} from '@headlessui/vue'

// 获取查询路由
const route = useRoute();
const isScrapOpen = ref(false)
const scrapReason = ref('')
const isCombinedScrap = ref(false) // 仅区分两种状态

// 动态配置
const dialogConfig = computed(() => {
  return isCombinedScrap.value ? {
    title: '包裹视频拍摄与物流单号不合格确认',
    placeholder: '请详细说明包裹视频拍摄或物流单号不合格的具体原因...',
    buttonText: '确认双项报废'
  } : {
    title: '报废视频拍摄不合格确认',
    placeholder: '请详细说明报废视频不合格的具体原因...',
    buttonText: '确认视频报废'
  }
})

// 打开弹窗逻辑
const showScrapDialog = () => {
  isCombinedScrap.value = formData.value.wlBillId?.trim() && formData.value.bffj?.trim() && formData.value.bffj !== ' '
  isScrapOpen.value = true
}


// 确认提交当前操作，不合适的确认
const confirmScrap = async () => {
  if (isCombinedScrap.value) {
    if (!scrapReason.value) {
      await ElMessageBox.alert('请输入当前寄回视频或者物流单号不合格的具体原因...', {
        type: "error",
        confirmButtonText: "确认",
        customClass: "my-custom-error",
      });
      return;
    }
    // 添加确认对话框并等待用户选择
    await ElMessageBox.confirm(
        `确定要对当前单据【` + formData.value.billId + "】的寄回视频或者物流单号驳回?",
        '确认通过',
        {
          confirmButtonText: '确定通过',
          cancelButtonText: '取消',
          type: 'warning'
        }
    )
  } else {
    if (!scrapReason.value) {
      await ElMessageBox.alert('请输入当前视频不合格的具体原因...', {
        type: "error",
        confirmButtonText: "确认",
        customClass: "my-custom-error",
      });
      return;
    }
    await ElMessageBox.confirm(
        `确定要对当前单据【` + formData.value.billId + "】的报废视频驳回?",
        '确认通过',
        {
          confirmButtonText: '确定通过',
          cancelButtonText: '取消',
          type: 'warning'
        }
    )
  }

  // 输入完之后 那么就将当前残次单信息传递 获取当前残次类型
  const type = localStorage.getItem('type');
  if (type) {
    formData.value.type = type;
  }

  const response = await axios.put('https://mms.mumuso.com:8214/dingTalkWebProject/reported/rejectVideoOrWlInfo', {
        billId: formData.value.billId,
        type: formData.value.type,
        staffId: formData.value.staffId,
        cgStaff: formData.value.cgStaff,
        bffj: formData.value.bffj,
        storeId: formData.value.storeId,
        itemName: formData.value.itemName,
        remark: formData.value.remark,
        className: formData.value.className,
        storeName: formData.value.storeName,
        staffName: formData.value.staffName,
        areaStaff: formData.value.areaStaff,
        wlBillId: formData.value.wlBillId,
        scrapReason: scrapReason.value,
        status: formData.value.status
      },
      {
        headers: {
          'Content-Type': 'application/json'
        }
      })

  if (response.data.code === 200) {
    await ElMessageBox.alert(response.data.msg, {
      type: "success",
      confirmButtonText: "确认",
      customClass: "my-custom-error",
    });
    isScrapOpen.value = false;
  } else {
    await ElMessageBox.alert(response.data.msg, {
      type: "error",
      confirmButtonText: "确认",
      customClass: "my-custom-error",
    });
    isScrapOpen.value = false;
  }
}


// 响应式数据
const formData = ref({
  storeName: '',
  reporter: '',
  billId: '',
  oaBillId: '',
  itemName: '',
  itemId: '',
  className: '',
  sellPrice: 0,
  uptime: '',
  remark: '',
  fj: '',
  staffId: '',
  areaStaff: '',
  wlBillId: '',
  shStatus: '',
  status: '',
  bffj: '',
  type: '',
  cgStaff: '',
  storeId: '',
  staffName: '',
  posQty: null
});

const opreationPersons = ref("MS02901")
// 响应式状态
const rejectDialogVisible = ref(false)
const rejectReason = ref('')
const rejectLoading = ref(false)

const buttonsDisabled = ref(true) // 控制按钮禁用状态

const loading = ref(true)
const error = ref(null)
const prefixUrl = ref("https://mms.mumuso.com:8214/dingTalkWebProject/api/file/");

const closeScrapDialog = () => {
  isScrapOpen.value = false
  scrapReason.value = ''
}

// 显示驳回弹窗
const showRejectDialog = () => {
  rejectReason.value = ''
  rejectDialogVisible.value = true
}

// 取消驳回
const cancelReject = () => {
  rejectDialogVisible.value = false
}

// 提交驳回
const submitReject = async () => {
  if (!rejectReason.value.trim()) {
    await ElMessageBox.alert('请输入当前残次单【' + formData.value.billId + '】驳回原因!', {
      type: "error",
      confirmButtonText: "确认",
      customClass: "my-custom-error",
    });
    return
  }

  rejectLoading.value = true
  try {
    const response = await axios.post('https://mms.mumuso.com:8214/dingTalkWebProject/reported/riskRejectReported', {
      billId: formData.value.billId,
      rejectReason: rejectReason.value,
      staffId: formData.value.staffId,
      storeId: formData.value.storeId,
      storeName: formData.value.storeName,
      cgStaff: formData.value.cgStaff,
      itemName: formData.value.itemName,
      remark: formData.value.remark,
      staffName: formData.value.staffName,
      areaStaff: formData.value.areaStaff
    })

    if (response.data.code === 200) {
      await ElMessageBox.alert(response.data.msg, {
        type: "success",
        confirmButtonText: "确认",
        customClass: "my-custom-error",
      });
      await fetchDefectDetail(formData.value.billId);
    } else {
      await ElMessageBox.alert(response.data.msg, {
        type: "error",
        confirmButtonText: "确认",
        customClass: "my-custom-error",
      });
    }
  } catch (error) {
    console.error(' 驳回请求失败:', error)
    await ElMessageBox.alert('驳回请求失败' + error, {
      type: "error",
      confirmButtonText: "确认",
      customClass: "my-custom-error",
    });
  } finally {
    rejectLoading.value = false
    rejectDialogVisible.value = false
  }
}
// 获取残次单详情
const fetchDefectDetail = async (billId) => {
  try {
    loading.value = true
    const response = await axios.get(`https://mms.mumuso.com:8214/dingTalkWebProject/reported/getReportedInfo/${billId}`)
    if (response.data.code === 200) {
      formData.value = response.data.data
      // 处理附件URL
      if (formData.value.fj) {
        formData.value.fj = prefixUrl.value + formData.value.fj
      }
      if (formData.value.bffj) {
        formData.value.bffj = prefixUrl.value + formData.value.bffj
      }
      // 检查staffId是否匹配
      const localStaffId = localStorage.getItem("staffId")
      if (opreationPersons.value && localStaffId && opreationPersons.value.toString() === localStaffId.toString()) {
        buttonsDisabled.value = false // 禁用按钮
      }
    } else {
      await ElMessageBox.alert(response.data.msg, {
        type: "error",
        confirmButtonText: "确认",
        customClass: "my-custom-error",
      });
    }

  } catch (err) {
    error.value = err.response?.data?.message || '获取数据失败'
    console.error(' 获取残次单详情失败:', err)
  } finally {
    loading.value = false
  }
}

// 审核通过
const handleApprove = async () => {
  try {
    // 添加确认对话框并等待用户选择
    await ElMessageBox.confirm(
        `确定要通过残次单【${formData.value.billId} 】的审核吗？`,
        '确认通过',
        {
          confirmButtonText: '确定通过',
          cancelButtonText: '取消',
          type: 'warning'
        }
    )

    const type = localStorage.getItem('type');
    if (type) {
      formData.value.type = type;
    }
    // 只有用户点击"确定通过"才会执行到这里
    const response = await axios.put(
        `https://mms.mumuso.com:8214/dingTalkWebProject/reported/riskApproveReported`,
        {
          billId: formData.value.billId,
          type: formData.value.type,
          staffId: formData.value.staffId,
          cgStaff: formData.value.cgStaff,
          bffj: formData.value.bffj,
          storeId: formData.value.storeId,
          itemName: formData.value.itemName,
          remark: formData.value.remark,
          className: formData.value.className,
          storeName: formData.value.storeName,
          staffName: formData.value.staffName,
          areaStaff: formData.value.areaStaff,
          wlBillId: formData.value.wlBillId
        },
        {
          headers: {
            'Content-Type': 'application/json'
          }
        }
    )

    if (response.data.code === 200) {
      await ElMessageBox.alert(response.data.msg, {
        type: "success",
        confirmButtonText: "确认",
        customClass: "my-custom-error",
      });
      await fetchDefectDetail(formData.value.billId);
    } else {
      throw new Error(response.data.msg || '审核操作失败')
    }

  } catch (error) {
    // 用户点击取消按钮
    if (error === 'cancel' || error.message?.includes('cancel')) {
      return // 静默退出，不显示错误
    }

    // 处理其他错误
    const errorMsg = error.response?.data?.message || error.message || '审核操作失败'
    ElMessage.error(` 审核失败: ${errorMsg}`)
    console.error(' 审核通过失败:', error)
  }
}

// 组件挂载时获取数据
onMounted(() => {
  // 从路由参数中获取残次单号
  const billId = route.query.billId;
  // 获取提报人编号
  const staffId = route.query.staffId;
  const type = route.query.type;
  localStorage.setItem("staffId", staffId);
  localStorage.setItem("type", type);

  if (billId) {
    fetchDefectDetail(billId)
  } else {
    error.value = '未提供残次单号'
    loading.value = false
  }
});
</script>

<style scoped>
/* 自定义滚动条 */
::-webkit-scrollbar {
  width: 6px;
  height: 6px;
}

::-webkit-scrollbar-thumb {
  background: #cbd5e1;
  border-radius: 3px;
}
</style>